<template>
  <a-modal
    :title="title"
    :width="900"
    :visible="visible"
    :confirm-loading="loading"
    @cancel="this.handelCancel"
    cancelText="取消"
    okText="保存"
    :destroyOnClose="true"
    :footer="null"
  >
    <!--<a-steps :current="current">
      <a-step v-for="item in steps" :key="item.title" :title="item.title" />
    </a-steps>-->
    <a-spin :spinning="spinning">
    <div class="steps-content">
      <div v-if="current === 0">
        <a-upload-dragger
          name="file"
          :file-list="fileList"
          :multiple="false"
          @change="handleChange"
          accept=".xls,.xlsx"
          :before-upload="beforeUpload"
          :showUploadList="true"
          :remove="handleRemove"
          :disabled="disabled"
          @reject="handleReject"
        >
          <p class="ant-upload-drag-icon">
            <a-icon type="inbox" />
          </p>
          <p class="ant-upload-text">
           点击或拖拽文件到此处上传
          </p>
          <p class="ant-upload-hint">
            支持10MB以内的xls、xlsx文件，内容在20000行和200列以内,只支持单个文件上传
          </p>
        </a-upload-dragger>
        <!--文件列表-->
        <!--<ul>
          <li v-for="(item, index) in fileList" :key="index">
            <div>{{ item.name }}</div>
            <div>{{ item.size }}</div>
          </li>
        </ul>-->

      </div>

      <div v-if="current === 1">
          <div class="flexRow bold alignLeft bottom10">
            <div class="flex">
                工作表字段
            </div>
            <div class="controlSeparate"></div>
            <div class="flex">
                Excel 列
            </div>
          </div>
          <a-form :form="form" v-if="rows.length > 0">
            <a-form-item class="bottom0" v-for="item in model.fields" :key="item.name">
              <a-form-item
                class="bottom0"
                :style="{ display: 'inline-block', width: 'calc(50% - 50px)' }"
              >
                <a-input
                  :defaultValue="item.alia"
                  :disabled="true"
                  style="color: #767676"
                />
              </a-form-item>
              <span :style="{ display: 'inline-block', width: '100px', textAlign: 'center' }">
              </span>
              <a-form-item
                class="bottom0"
                :style="{ display: 'inline-block', width: 'calc(50% - 50px)' }">
                <a-select default-value="" v-decorator="[item.name, {initialValue: ''}]">
                  <a-select-option value="">
                    请选择
                  </a-select-option>
                  <a-select-option :value="cell.columnNumber" v-for="cell in row['cells']" :key="cell.columnNumber">
                    {{ cell.value }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-form-item>
          </a-form>
        </div>
    </div>
    </a-spin>

    <div class="steps-action">
      <a-button v-if="current > 1" @click="prev">
        上一步
      </a-button>
      <a-button v-if="current < steps.length - 1 && uploadState" style="margin-left: 8px" type="primary" @click="next">
        下一步
      </a-button>
      <a-button
        v-if="current === steps.length - 1"
        type="primary"
        style="margin-left: 8px"
        @click="handleImport"
      >
        开始导入
      </a-button>
    </div>

    <!--取消导入 对话框-->
    <a-modal
      :visible="false"
      @cancel="this.handelCancel"
      :destroyOnClose="true"
    >
    </a-modal>

  </a-modal>
</template>

<script>
  import { uploadExcel, previewExcel } from '@/api/worksheet'

  export default {
    name: 'ImportExcelData',
    props: {
      visible: {
        type: Boolean,
        required: true
      },
      loading: {
        type: Boolean,
        default: () => false
      },
      model: {
        type: Object,
        default: () => null
      }
    },
    data () {
      return {
        sheetNumber: 0, // 视图编号
        form: this.$form.createForm(this),
        rows: [],
        rowNumber: 0, // 表头的行数
        filePath: '',
        uploadState: false,
        disabled: false,
        fileList: [],
        current: 0,
        spinning: false,
        steps: [
          {
            title: '上传 Excel',
            content: 'First-content',
          },
          {
            title: '字段映射',
            content: 'Last-content',
          },
        ],
      };
    },
    computed: {
      row: function () {
        return this.rows[this.rowNumber]
      },
      title: function () {
        return `数据导入 - ${ this.steps[this.current].title } （${ this.current + 1 }/${ this.steps.length }）`
      }
    },
    methods: {
      next () {
        if (this.fileList.length === 0) {
          this.$message.warn("请先选择一个文件")
          return
        }

        if (this.current === 0) {
          this.handlePreviewExcel()
        }

        this.current++;
      },
      prev () {
        this.current--;
      },
      handelCancel () {
        this.backToDefaultValue()

        this.$emit('cancel')
      },
      handleChange (info) {
        /*let fileList = [...info.fileList]
        fileList = fileList.splice(-1)

        const file = fileList[0]
        this.checkFile(file, fileList)*/
      },
      checkFile (file, fileList) {
        if (file) {
          const isJpgOrPng = file.name.endsWith(".xls") || file.name.endsWith(".xlsx")
          if (!isJpgOrPng) {
            this.$message.error('You can only upload XLS or XLSX file!');
          }
          const isLt2M = file.size / 1024 / 1024 < 10;
          if (!isLt2M) {
            this.$message.error('File must smaller than 10MB!');
          }

          if (!isJpgOrPng || !isLt2M) {
            this.fileList = []
            return false
          }

          this.fileList = fileList

          return true
        }
      },
      handleReject (fileList) {
        this.$message.warn("文件格式不符合")
      },
      beforeUpload (file, fileList) {
        const checkResult = this.checkFile(file, fileList)
        // 上传文件
        checkResult && this.handleUpload()
        return false
      },
      handleRemove (file) {
        this.fileList = []
      },
      handleUpload () {
        const file = this.fileList[0]
        const formData = new FormData()
        formData.append("file", file)
        this.spinning = true
        uploadExcel(formData).then(res => {
          this.spinning = false
          if (res.code === 200) {
            this.$message.info(`${file.name} 上传成功`)
            this.uploadState = true
            this.filePath = res.data.url
            if (!this.filePath.startsWith('http')) {
              this.filePath = `${window.location.protocol}//${window.location.hostname}:2020${this.filePath}`
            }
          } else {
            this.$message.error(`${file.name} 上传失败`)
          }
        })
      },
      handlePreviewExcel () {
        if (this.filePath === '') {
          return
        }
        const param = {
          filePath: this.filePath
        }
        this.spinning = true
        previewExcel(param).then(res => {
          this.spinning = false
          if (res.code === 200) {
            this.rows = res.data
            // TODO 这里后面再加上可以自由选择某一行做表头，暂时用第一行做表头
            this.rowNumber = 0
          }
        })
      },
      handleImport () {
        this.$emit('ok', {
          sheetNumber: this.sheetNumber,
          rowNumber: this.rowNumber,
          filePath: this.filePath
        })

        this.backToDefaultValue()
      },
      backToDefaultValue () {
        this.current = 0
        this.fileList = []
        this.rows = []
        this.uploadState = false
        this.filePath = ''
      }
    }
  }
</script>

<style lang="less" scoped>
  @import "../worksheet";

  .steps-content {
    border-radius: 6px;
    min-height: 300px;
    text-align: center;
  }

  .steps-action {
    margin-top: 24px;
    text-align: right;
  }

</style>
